import requests
from flask import Blueprint
from config import *
from model.user import User
from service.user_resume_service import UserResumeService
from service.user_service import UserService
from utils.securtiy import *
from utils.work_db import get_session
from utils.work_log import get_logger
from service.user_point_service import UserPointService
from model.user_point import UserPoint
from model.user_resume import UserResume

api = Blueprint('user_api', __name__, url_prefix='/api/v1/user')
log = get_logger(__name__)


@api.route('/get_user/<user_id>', methods=['GET'])
@login_required
def get_user(user_id, **kwargs):
    """
    获得我的信息
    :param user_id:
    :param kwargs:
    :return:
    """
    session = get_session()
    user_service = UserService(session)
    q_user = user_service.get_by_id(user_id)
    if q_user:
        return json_response(q_user.json(), msg='')
    else:
        return json_response(None, msg='信息不存在', code=-1)


@api.route('/update_user', methods=['POST'])
@login_required
def update_user(**kwargs):
    """
    更新个人信息以及简历信息
    :param kwargs:
    :return:
    """
    params = request.json
    if not params["userid"]:
        return json_response(None, msg='用户id不能为空', code=-1)
    if not params["tel"]:
        return json_response(None, msg='手机号不能为空', code=-1)
    if not params["real_name"]:
        return json_response(None, msg='真实姓名不能为空', code=-1)
    if not params["nick_name"]:
        return json_response(None, msg='昵称不能为空', code=-1)
    session = get_session()
    try:
        user_service = UserService(session)
        point_service = UserPointService(session)
        q_user = user_service.get_by_id(int(params["userid"]))
        if q_user:
            q_user.tel = str(params["tel"])
            q_user.real_name = str(params["real_name"])
            q_user.nick_name = str(params["nick_name"])
            q_user.email = str(params["email"])

            points = UserPoint()
            points.user_id = q_user.user_id
            points.openid = q_user.openid
            points.points_code = 2
            point_service.add_points(points)

            session.commit()
            session.close()
            return json_response(None, msg='修改成功', code=1)
        else:
            return json_response(None, msg='用户信息不存在', code=-1)
    except Exception as ex:
        log.error("update_user:" + str(ex))
        return json_response(None, msg='修改失败', code=-1)


"""
{
"user_id":11,
"sec_pub_tel":1/2,
"sec_pub_recieve":1/2,
"message_push":1/2
}
1:启动 2:不启动
1:允许 2:不允许

"""


@api.route('/update_private', methods=['POST'])
@login_required
def update_private(**kwargs):
    """
    安全设置-隐私设置和消息通知设置
    :param kwargs:
    :return:
    """
    params = request.json
    if not params or not params["user_id"]:
        return json_response(None, msg='用户id不能为空', code=-1)
    user_id = int(params["user_id"])

    sec_pub_tel = sec_pub_recieve = message_push = None
    if params.get("sec_pub_tel", "0"):
        sec_pub_tel = int(params.get("sec_pub_tel", "0"))
    if params.get("sec_pub_recieve", "0"):
        sec_pub_recieve = int(params.get("sec_pub_recieve", "0"))
    if params.get("message_push", "0"):
        message_push = int(params.get("message_push", "0"))
    session = get_session()
    user_service = UserService(session)
    q_user = user_service.get_by_id(user_id)
    if not q_user:
        return json_response(None, msg='此用户不存在', code=-1)

    # 1:启动 2:不启动
    if sec_pub_tel == 1 or sec_pub_tel == 2:
        q_user.sec_pub_tel = sec_pub_tel
    if sec_pub_recieve == 1 or sec_pub_recieve == 2:
        q_user.sec_pub_recieve = sec_pub_recieve
    if message_push == 1 or message_push == 2:
        q_user.message_push = message_push
    session.commit()
    return jsonify({'msg': '设置成功', 'code': 1})


"""
inparam:
{
"code":"123",
"user":{
"avatarUrl":'',
"nickName":'',
"gender":''}//从微信获得用户信息
}
"""


@api.route('/wx_login', methods=['POST'])
def wx_login():
    """
    微信登录
    :return:
    """
    session = get_session()
    params = request.json
    if params and params.get("code"):
        js_code = params["code"]
        wx_param = {}
        wx_param.update(dict(WX_CONFIG))
        wx_param.update({"js_code": js_code})
        send_r = requests.get(wx_session_url, params=wx_param, timeout=5)
        wx_result = send_r.json()
        if wx_result:
            wx_openid = wx_result["openid"]
            log.info("login=================wx_openid:" + str(wx_openid))
            # session_key = wx_result["session_key"]
            union_id = wx_result.get("unionid")
            wx_user = params["user"]
            q_user_service = UserService(session)
            point_service = UserPointService(session)
            q_user = q_user_service.get_by_openid(wx_openid, user_type=1)
            if q_user and q_user.openid:
                t_user = {"user_id": q_user.user_id,
                          "tel": q_user.tel,
                          "wx_openid": wx_openid}
                m_token = create_jwt(t_user)
                j_user = {"token": m_token,
                          "user_id": q_user.user_id,
                          "tel": q_user.tel}

                points = UserPoint()
                points.openid = wx_openid
                points.points_code = 3
                point_service.add_points(points)
                session.commit()
                q = session.query(UserResume)
                q_record = q.filter(UserResume.user_id == q_user.user_id).first()
                if q_record:
                    j_user["has_resume"] = 1
                else:
                    j_user["has_resume"] = 0
                return json_response(j_user, msg='登陆成功', code=1)
            else:
                user = User()
                user.openid = wx_openid
                if wx_user:
                    user.header_img = wx_user["avatarUrl"]
                    user.wx_nick_name = wx_user["nickName"]
                    user.gender = wx_user["gender"]
                    user.unionid = union_id
                    user.user_type = 1
                    q_user_service.add_user(user)

                points = UserPoint()
                points.openid = wx_openid
                points.points_code = 1
                point_service.add_points(points)

                session.commit()
                q_user = q_user_service.get_by_openid(wx_openid, user_type=1)
                t_user = {"user_id": q_user.user_id,
                          "tel": q_user.tel,
                          "wx_openid": wx_openid}
                token = create_jwt(t_user)
                j_user = {"token": token,
                          "user_id": q_user.user_id,
                          "tel": q_user.tel}
                ##是否存在简历
                q = session.query(UserResume)
                q_record = q.filter(UserResume.user_id == q_user.user_id).first()
                if q_record:
                    j_user["has_resume"] = 1
                else:
                    j_user["has_resume"] = 0
                return json_response(j_user, msg='登陆成功', code=1)
        else:
            return json_response(None, msg='登陆错误!', code=-1)
    else:
        return json_response(None, msg='授权码code为空!', code=-1)


@api.route('/get_resume/<user_id>', methods=['GET'])
@login_required
def get_resume(user_id, **kwargs):
    """
    获得简历详情
    :param user_id:
    :param kwargs:
    :return:
    """
    session = get_session()
    resume_service = UserResumeService(session)
    resume = resume_service.get_resume_by_user_id(user_id)
    if resume:
        data = {"user_id": resume.user_id,
                "real_name": resume.user_name,
                "resume_name": resume.user_name,
                "tel": resume.tel,
                "ages": resume.age,
                "work_intention": resume.work_intention,
                "work_history": resume.work_history
                }
        return json_response(data, msg='', code=1)
    else:
        return json_response(None, msg='用户不存在', code=-1)


@api.route('/get_point_dict', methods=['GET'])
def get_point_dict(**kwargs):
    """
    获得积分字典
    :param kwargs:
    :return:
    """
    session = get_session()
    point_service = UserPointService(session)
    result = point_service.get_point_dict()
    return json_response(result, msg='', code=1)


@api.route('/get_user_point', methods=['GET'])
@login_required
def get_user_point(**kwargs):
    """
    获得个人积分明细
    :param kwargs:
    :return:
    """
    session = get_session()
    user_id = get_user_id()
    point_service = UserPointService(session)
    result = point_service.get_points_by_user_id(user_id)
    return json_response(result, msg='', code=1)
